﻿using Brc_PaaS.Common.Helper;
using Brc_PaaS.Common.Model.Apollo;
using Brc_PaaS.Common.Model.Basic;
using Newtonsoft.Json;
using System.Collections.Generic;


namespace Brc_PaaS.Core.Apollo.Service.Implement
{
    public class ApolloConfigService : IApolloConfigService
    {
        /// <summary>
        /// 新增配置接口
        /// </summary>
        /// <param name="configInfoDto"></param>
        /// <returns></returns>
        public ResponseModel<ConfigInfoDto> AddConfig(CreateOrUpdateConfigInfoDto configInfoDto)
        {
            var result = new ResponseModel<ConfigInfoDto> { IsSuccess = false };
            if (configInfoDto == null)
            {
                result.Msg = "参数对象为空";
                return result;
            }

            string url = string.Format("http://{0}/openapi/v1/envs/{1}/apps/{2}/clusters/{3}/namespaces/{4}/items",
                configInfoDto.Portal_address, configInfoDto.Env, configInfoDto.AppId, configInfoDto.ClusterName, configInfoDto.NamespaceName);
            var tokenHeader = GetTokenHeader(configInfoDto.Token);
            string postData = JsonConvert.SerializeObject(configInfoDto);
            var strConfigDto = HttpHelper.HttpPost(url, postData, tokenHeader);
            return ProcessResult<ConfigInfoDto>(strConfigDto);
        }
        /// <summary>
        /// 删除配置接口
        /// </summary>
        /// <param name="deleteConfigDto"></param>
        public BaseResponseModel DeleteConfig(DeleteConfigDto deleteConfigDto)
        {
            if (deleteConfigDto == null)
            {
                return new BaseResponseModel() { IsSuccess = false, Msg = "参数对象为空" };
            }

            string url = string.Format("http://{0}/openapi/v1/envs/{1}/apps/{2}/clusters/{3}/namespaces/{4}/items/{5}?operator={6}",
                deleteConfigDto.Portal_address, deleteConfigDto.Env, deleteConfigDto.AppId, deleteConfigDto.ClusterName,
                deleteConfigDto.NamespaceName, deleteConfigDto.Key, deleteConfigDto.Operator);
            var tokenHeader = GetTokenHeader(deleteConfigDto.Token);
            string postData = JsonConvert.SerializeObject(deleteConfigDto);
            var result = HttpHelper.HttpDelete(url, postData, tokenHeader);
            return ProcessResult(result);
        }

        /// <summary>
        /// 获取某个Namespace当前生效的已发布配置接口
        /// </summary>
        /// <param name="conditionDto"></param>
        /// <returns></returns>
        public ResponseModel<ReleaseConfigInfoDto> GetEffectiveConfigInfo(SingleNamespaceConditionDto conditionDto)
        {
            if (conditionDto == null)
            {
                return new ResponseModel<ReleaseConfigInfoDto>() { IsSuccess = false, Msg = "参数对象为空" };
            }

            string url = string.Format("http://{0}/openapi/v1/envs/{1}/apps/{2}/clusters/{3}/namespaces/{4}/releases/latest",
                conditionDto.Portal_address, conditionDto.Env, conditionDto.AppId, conditionDto.ClusterName,
                conditionDto.NamespaceName);
            var tokenHeader = GetTokenHeader(conditionDto.Token);
            string postData = JsonConvert.SerializeObject(conditionDto);
            var strReleaseConfigInfo = HttpHelper.HttpGet(url, tokenHeader);
            return ProcessResult<ReleaseConfigInfoDto>(strReleaseConfigInfo);
        }
        /// <summary>
        ///  发布配置接口
        /// </summary>
        /// <param name="conditionDto"></param>
        /// <returns></returns>
        public ResponseModel<ReleaseConfigInfoDto> ReleaseConfig(ReleaseConfigConditionDto conditionDto)
        {
            if (conditionDto == null)
            {
                return new ResponseModel<ReleaseConfigInfoDto>() { IsSuccess = false, Msg = "参数对象为空" };
            }

            string url = string.Format("http://{0}/openapi/v1/envs/{1}/apps/{2}/clusters/{3}/namespaces/{4}/releases",
                conditionDto.Portal_address, conditionDto.Env, conditionDto.AppId, conditionDto.ClusterName,
                conditionDto.NamespaceName);
            var tokenHeader = GetTokenHeader(conditionDto.Token);
            string postData = JsonConvert.SerializeObject(conditionDto);
            var strConfigInfoDto = HttpHelper.HttpPost(url, postData, tokenHeader);
            return ProcessResult<ReleaseConfigInfoDto>(strConfigInfoDto);
        }
        /// <summary>
        /// 修改配置接口
        /// </summary>
        /// <param name="configInfoDto"></param>
        public BaseResponseModel UpdateConfig(CreateOrUpdateConfigInfoDto configInfoDto)
        {
            if (configInfoDto == null)
            {
                return new BaseResponseModel() { IsSuccess = false, Msg = "参数对象为空" };
            }

            string url = string.Format("http://{0}/openapi/v1/envs/{1}/apps/{2}/clusters/{3}/namespaces/{4}/items/{5}",
                configInfoDto.Portal_address, configInfoDto.Env, configInfoDto.AppId, configInfoDto.ClusterName, configInfoDto.NamespaceName, configInfoDto.Key);
            var tokenHeader = GetTokenHeader(configInfoDto.Token);
            string postData = JsonConvert.SerializeObject(configInfoDto);
            var result = HttpHelper.HttpPut(url, postData, tokenHeader);
            return ProcessResult(result);
        }

        private ResponseModel<T> ProcessResult<T>(string result)
        {
            string message = GetMessage(result);
            if (!string.IsNullOrWhiteSpace(message))
            {
                return new ResponseModel<T>()
                {
                    Msg = message,
                    IsSuccess = false
                };
            }
            var configInfoDto = JsonConvert.DeserializeObject<T>(result);
            return new ResponseModel<T>
            {
                IsSuccess = true,
                Data = configInfoDto
            };
        }

        private BaseResponseModel ProcessResult(string result)
        {
            string message = GetMessage(result);
           
            if (!string.IsNullOrWhiteSpace(message))
            {
                return new BaseResponseModel()
                {
                    Msg = message,
                    IsSuccess = false
                };
            }
            
            return new BaseResponseModel
            {
                IsSuccess = true
               
            };
        }

        public string GetMessage(string result)
        {
            string message = string.Empty;
            if (!string.IsNullOrWhiteSpace(result))
            {
                var exceptionInfoDto = JsonConvert.DeserializeObject<ApolloExceptionInfoDto>(result);
                if (exceptionInfoDto != null && !string.IsNullOrWhiteSpace(exceptionInfoDto.Message))
                {
                    message = exceptionInfoDto.Message;
                }
            }
            return message;
        }


        public Dictionary<string, string> GetTokenHeader(string token)
        {
            Dictionary<string, string> keyValues = new Dictionary<string, string>();
            keyValues.Add("Authorization", token);
            return keyValues;
        }
    }
}

